#include "Common.h"
namespace xncc {
namespace common {
    auto exists(const std::string& file) -> bool
    {
        if (file.empty()) {
            return false;
        }
        struct stat fst = {};
        return ::stat(file.data(), &fst) == 0;
    }

    auto createPath(const std::string& spath) -> bool
    {
        if (exists(spath)) {
            return true;
        }
        bool        ret    = false;
        const char* path   = spath.c_str();
        int         length = static_cast<int>(strlen(path));
        std::string createPath;
        for (const char* pos = path; (pos - path) <= length; ++pos) {
            createPath += *pos;
            if (*pos == '/' || (pos - path) == length) {
                ret = mkdir(createPath.c_str(), 0755) == 0;
            }
        }
        return ret;
    }

    auto unixtimestampToStr(int64_t tms) -> std::string
    {
        const time_t ts_s    = tms / 1000000000LL;
        const int    ts_ms   = static_cast<int>((tms % 1000000000LL) / 1000000LL);
        struct tm*   tm1     = localtime(&ts_s);
        char         buf[64] = {0};
        auto         ret = snprintf(buf, 64, "%04d-%02d-%02d_%02d_%02d_%02d.%03d", tm1->tm_year + 1900, tm1->tm_mon + 1,
                                    tm1->tm_mday, tm1->tm_hour, tm1->tm_min, tm1->tm_sec, ts_ms);
        (void)ret;
        return std::string(buf);
    }

    auto timevalToStr(const struct timeval* tmv) -> std::string
    {
        const int  tus     = static_cast<int>(tmv->tv_usec);
        struct tm* tm1     = localtime(&(tmv->tv_sec));
        char       buf[64] = {0};
        auto       ret = snprintf(buf, 64, "%04d-%02d-%02d_%02d:%02d:%02d.%06d", tm1->tm_year + 1900, tm1->tm_mon + 1,
                                  tm1->tm_mday, tm1->tm_hour, tm1->tm_min, tm1->tm_sec, tus);
        (void)ret;
        return std::string(buf);
    }

    auto timeNowStr() -> std::string
    {
        struct timeval tmv = {};
        gettimeofday(&tmv, nullptr);
        return timevalToStr(&tmv);
    }

    auto appendPath(const std::string& path, const std::string& file) -> std::string
    {
        const char last = path.back();
        if (last == '/') {
            return std::string(path) + file;
        }
        return std::string(path) + '/' + file;
    }
}  // namespace common
}  // namespace xncc